<template>
    <div
      :style="'height: ' + innerHeight + 'px'"
      v-loading="loading"
      element-loading-text="页面正在加载中..."
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :element-loading-lock="true"
    >
      <!--分页组件-->
      <pager
        :tbcols="tbcols"
        :tbdata="tbdata"
        :Pagination="Pagination"
        :reloadPagerData="reloadPagerData"
        ref="tbpager"
      >
        <template #serchInner>
          <el-form label-width="120px" :model="editData">
            <el-row :gutter="20" style="margin-top: -10px">
              <el-col :span="5">
                <el-form-item label="保险公司名称">
                  <el-input v-model="serchParam.mingchengLike" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="负责人">
                  <el-input v-model="serchParam.fuzerenLike" size="small"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
        <template #tbColSlot>
          <el-table-column label="设置" width="70">
            <template #default="scope">
              <el-button type="primary" size="small" @click="updateRow(scope.row)">选择</el-button>
            </template>
          </el-table-column>
          <template v-if="bthide">
            <el-table-column label="设置" width="70">
              <template #default="scope">
                <el-button type="danger" size="small" @click="bxgstbSelectbt(scope.row)">添加</el-button>
              </template>
            </el-table-column>
          </template>
        </template>
        <!--分页控件标题区域-->
        <template #soltTitle> 保险公司资料管理 </template>
        <!--表格操作按钮区域  以具名插槽的方式使用-->
        <template #slotBts>
          <!--
          <el-button type="primary" @click="getSelectRow">选择</el-button>
          <el-button type="info">编辑</el-button>      
          
            <el-button type="success" @click="add">新建</el-button>
            <el-button type="danger" @click="stop">禁用/启用</el-button>
          -->
          <template v-for="(item, index) in buttons" :key="index">
            <template v-if="item.value == 'Search'">
              <el-button
                @click="reloadPagerData"
                :style="'color:#000;background-color:' + item.color + ';'"
                >查询</el-button
              >
            </template>
            <template v-else>
              <el-button
                @click="methodUtils(item.value)"
                :style="'color:#fff;background-color:' + item.color + ';'"
                >{{ item.name }}</el-button
              >
            </template>
          </template>
        </template>
      </pager>
  
      <div
        style="
          margin-left: 20px;
          margin-right: 20px;
          margin-top: 20px;
          background-color: #eeeeee;
          padding: 5px;
          display: flex;
          justify-content: space-between;
        "
      >
        <div style="align-self: flex-start" class="title">
          <div class="iconfont icon-liebiao" style="font-size: 20px"></div>
          <div style="margin-left: 5px">保险公司资料添加/修改</div>
        </div>
        <div style="align-self: flex-end"></div>
      </div>
  
      <div style="border: 1px solid #ccc; margin-left: 20px; margin-right: 20px">
        <el-form label-width="120px" :model="editData">
          <el-row :gutter="20" style="margin-top: 10px">
            <el-col :span="6">
              <el-form-item label="保险公司名称">
                <el-input v-model="editData.mingcheng" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="电话">
                <el-input v-model="editData.dianhua" size="small"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20" style="margin-top: -15px">            
            <el-col :span="6">
              <el-form-item label="负责人">
                <el-input v-model="editData.fuzeren" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="地址">
                <el-input v-model="editData.dizhi" size="small"></el-input>
              </el-form-item>
            </el-col>            
          </el-row>
  
          <el-row :gutter="20" style="margin-top: -15px">
            <el-col :span="18">
              <el-form-item label="">
                <div style="color: red">保存档案时请选择右上角的【新增】、【编辑】</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </template>
  <script lang="ts" setup name="miyaouser">
  import http from '@/api/http'
  import { onMounted, ref, reactive } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import pager from '@/components/zjc/pager.vue'
  import { type Paginations } from '@/model/pagination.ts'
  import store from '@/store/index.js'
  import { useRoute } from 'vue-router'
  import permission from '@/api/zjc/zjcpermission.js'
  
  let serchParam = reactive({ carnoLike: null, knameLike: null, chexingLike: null, beizhuLike: null })
  const buttons = reactive([])
  const mx = ref()
  const tbpager = ref(null)
  const editData = reactive({})
  
  const loading = ref(false)
  const innerHeight = ref(window.innerHeight - 140)
  
  const mxHeight = ref(innerHeight.value * 0.7)
  
  const dialogVisible_Zhanghao = ref(false)
  
  const selectZhanghao = () => {
    dialogVisible_Zhanghao.value = true
  }
  
  const updateRow = (row) => {
    Object.keys(row).forEach(function (key) {
      editData[key] = row[key]
    })
  }
  
  //页面初始化加载完成钩子
  onMounted(async () => {
    //获取当前页面路由
    const route = useRoute()
    //alert(route.path);
    //获取缓存中的权限信息
    let store_permission = store.getters.getPermission(route.path)
    //alert(JSON.stringify(store_permission));
    //在权限信息中获取按钮
    var permissionButtons = permission.getButtons(route.path)
    if (permissionButtons) {
      //2020.03.31添加深拷贝按钮组
      permissionButtons.forEach((p) => {
        let _obj = {}
        for (const key in p) {
          _obj[key] = p[key]
        }
        buttons.push(_obj)
      })
      // this.buttons.push(...permissionButtons);
    }
    //alert(JSON.stringify(buttons))
  
    await reloadPagerData(Pagination)
  
    await http
      .get('api/qx_bxgs/GetObjectJson', {}, false, {
        params: { Id: '00000000-0000-0000-0000-000000000000' }
      })
      .then((res) => {
        if (res.Tag == 1) {
          Object.assign(editData, res.Data)
        }
      })
  })
  
  //定义分页参数
  let Pagination: Paginations = reactive({
    Sort: 'CreateDate',
    SortType: ' desc ',
    PageIndex: 1,
    PageSize: 3,
    TotalCount: 0
  })
  //定义表格列的信息
  let tbcols: any[] = [
    { prop: 'mingcheng', label: '保险公司名称', width: 120, align: 'left' },
    { prop: 'dianhua', label: '电话', width: 220, align: 'center' },
    { prop: 'fuzeren', label: '负责人', width: 250, align: 'center' },
    { prop: 'dizhi', label: '地址', width: 180, align: 'center' }
  ]
  //定义表格数据
  let tbdata: any[] = reactive([])
  
  //获取选中行
  /**
   * vue3 语法糖的方法中没法直接使用this.$refs
   * 解决方案：定义一个变量，并且变量的名字和要获取数据的子组件的ref的名字一致
   * 然后使用变量名.value.子组件中的方法名或变量名 即可调用子组件中的数据。
   * 注意子组件中调用的数据需要对外暴漏：defineExpose({dataonLineListSelections});
   */
  const getSelectRow = () => {
    let selectRowsData = tbpager.value.dataonLineListSelections
    //alert(JSON.stringify(selectRowsData))
    return selectRowsData
  }
  
  const clearSelectRow = async () => {
    await reloadPagerData(Pagination)
  }
  
  //重新执行分页
  const reloadPagerData = async (Pagination: Paginations) => {
    loading.value = true
    await loadData().then((res) => {
      tbdata.splice(0, tbdata.length)
      tbdata.push(...res)
      loading.value = false
    })
  }
  
  async function loadData() {
    //第一步：加载分页数据
    const arr = await loadPagerData()
    //第二步：追加分页数据属性
    /*
      var i = 0
      for (i = 0; i < arr.length; i++) {
        var item = arr[i]
        Object.assign(arr[i], {
          DisableUseValue: item.DisableUse == 1 ? '否' : '是',
          UserName: await GetColValueByKey('sys_user', 'UserName', 'User_Id', item.UserId)
        })
      }*/
    return arr
  }
  
  async function loadPagerData() {
    const arr = []
    const res = await http.get('api/qx_bxgs/GetPageDataZjc', {}, false, {
      params: Object.assign(Pagination, serchParam)
    })
    if (res.Tag == 1) {
      //alert(JSON.stringify(res.Data));
      arr.push(...res.Data)
      Pagination.TotalCount = res.Total
    } else {
      ElMessage({
        message: '系统异常，操作失败！',
        type: 'error'
      })
    }
    return arr
  }
  
  async function GetColValueByKey(
    tableName: string,
    selectColName: string,
    whereKey: string,
    whereKeyValue: string
  ) {
    /**
     * 这里注意 第三个参数一定要设置为false
     * 设置为false即关闭loading动画加载效果
     * 设置它为false就会避免页面在加载的时候不断的闪烁
     */
    const result = await http.get('api/sys/GetColValueByKey', {}, false, {
      params: {
        tableName: tableName,
        selectColName: selectColName,
        whereKey: whereKey,
        whereKeyValue: whereKeyValue
      }
    })
    return result
  }
  
  //增删改查方法综合调度
  const methodUtils = async (category) => {
    //alert(category)
    if (category == 'Add') {
      editData.Id = '00000000-0000-0000-0000-000000000000'
      //alert(JSON.stringify(editData));
      detailSave()
    } else if (category == 'DisableUse') {
      stop()
    } else if (category == 'Delete') {
      del()
    } else if (category == 'Update') {
      if (editData.Id == '00000000-0000-0000-0000-000000000000' || editData.Id == null) {
        ElMessage({
          message: '尚未选择要修改的配件！',
          type: 'error'
        })
        return
      }
      detailSave()
    }
  }
  
  //用户删除
  const del = async () => {
    let selectRowsData = tbpager.value.dataonLineListSelections
    if (selectRowsData.length != 1) {
      ElMessage({
        message: '只能选择至少1行数据！',
        type: 'error'
      })
      return
    }
  
    try {
      await ElMessageBox.confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // 删除操作
      const res = await http.get('api/qx_bxgs/DeleteFromJson', {}, true, {
        params: {
          id: selectRowsData[0].Id
        }
      })
  
      if (res.Tag == 1) {
        ElMessage({
          message: '数据删除成功!',
          type: 'success'
        })
        await reloadPagerData(Pagination)
      } else {
        ElMessage({
          message: '系统错误，操作失败！',
          type: 'error'
        })
      }
    } catch (err) {
      // 用户取消了删除
      //console.log('取消了删除');
    }
  }
  
  //禁用与开启
  const stop = async () => {
    let selectRowsData = tbpager.value.dataonLineListSelections
    if (selectRowsData.length != 1) {
      ElMessage({
        message: '只能选择至少1行数据！',
        type: 'error'
      })
      return
    }
  
    const res = await http.get('api/miyaouser/StopFormJson', {}, true, {
      params: {
        Miyao_Id: selectRowsData[0].Miyao_Id
      }
    })
  
    if (res.Tag == 1) {
      ElMessage({
        message: '操作成功，该用户已被禁用或启用!',
        type: 'success'
      })
      await reloadPagerData(Pagination)
    } else {
      ElMessage({
        message: '系统错误，操作失败！',
        type: 'error'
      })
    }
  }
  
  //明细保存
  const detailSave = async () => {
    //alert(JSON.stringify(editData));
    const res = await http.post('api/qx_bxgs/SaveFormJson', editData, true)
    if (res.Tag == 1) {
      ElMessage({
        message: '操作成功！',
        type: 'success'
      })
  
      /*
      Object.keys(editData).forEach(function (key) {
        editData[key] = null
      })
      */
      await http
      .get('api/qx_bxgs/GetObjectJson', {}, false, {
        params: { Id: '00000000-0000-0000-0000-000000000000' }
      })
      .then((res) => {
        if (res.Tag == 1) {
          Object.assign(editData, res.Data)
        }
      })
  
      await reloadPagerData(Pagination)
    } else {
      ElMessage({
        message: res.Message,
        type: 'error'
      })
    }
  }
  
  defineExpose({ getSelectRow, clearSelectRow })
  
  const props = defineProps({
    bthide: Boolean,
    bxgstbSelectbt: Function
  })
  
  //let props = defineProps(['bthide','tbSelectbt']);
  </script>
  
  <style scoped>
  .title {
    display: flex;
    padding: 3px;
    padding-left: 5px;
    padding-right: 5px;
    border-bottom: 1px solid #999;
    margin-left: 10px;
  }
  </style>
  